package com.wx.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.thoughtworks.xstream.XStream;
import com.wx.model.*;
import com.wx.model.message.*;
import com.wx.model.templatemessage.First;
import com.wx.model.templatemessage.Keyworld;
import com.wx.model.templatemessage.Remark;
import com.wx.model.templatemessage.WxTemplateMessage;
import com.wx.model.weather.*;
import com.wx.repository.FastDFSFileRepository;
import com.wx.repository.UserRepository;
import com.wx.repository.UserTextRepository;
import com.wx.service.WXService;
import com.wx.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.ServletInputStream;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author ：LiuShihao
 * @date ：Created in 2020/10/2 1:12 下午
 * @desc ：
 */
@Slf4j
@Service
public class WXServiceImpl implements WXService {
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    BDUtil bdUtil;
    @Autowired
    UserRepository userRepository;
    @Autowired
    FastDFSFileRepository fastDFSFileRepository;
    @Value("${token.value}")
    private String token;
    @Autowired
    NewUtil newUtil;
    @Autowired
    UserTextRepository userTextRepository;

    private static Token accessToken;

    /**
     * （私有方法）获取Token，并存储起来
     */
    private static void getAccessToken() {
        accessToken = CommonUtil.getToken();
    }

    /**
     * 向外暴露获取AccessToken的方法
     *
     * @return 如果Token过期或者为空，重新获取Token
     */
    public static String getToken() {
        if (accessToken == null || accessToken.isExpired()) {
            getAccessToken();
        }
        return accessToken.getAccessToken();
    }

    /**
     * 40001	获取 access_token 时 AppSecret 错误，或者 access_token 无效。请开发者认真比对 AppSecret 的正确性，或查看是否正在为恰当的公众号调用接口
     * 42001	access_token 超时，请检查 access_token 的有效期，请参考基础支持 - 获取 access_token 中，对 access_token 的详细机制说明
     *
     * @return
     */
    public String getRedisToken() {
        String accessToken = (String) redisUtils.get("WX_ACCESS_Token");
        log.info("缓存微信token:" + accessToken);
        if (StringUtils.isEmpty(accessToken)) {
            accessToken = CommonUtil.getToken().getAccessToken();
            log.info("获取微信token:" + accessToken);
            if (!StringUtils.isEmpty(accessToken)) {
                redisUtils.set("WX_ACCESS_Token", JSON.toJSON(accessToken), 7200);
            }
        }
        return accessToken;
    }

    /**
     * 开发者通过检验signature对请求进行校验（下面有校验方式）。
     * 若确认此次GET请求来自微信服务器，请原样返回echostr参数内容，则接入生效，成为开发者成功，否则接入失败。加密/校验流程如下：
     * <p>
     * 1）将token、timestamp、nonce三个参数进行字典序排序
     * 2）将三个参数字符串拼接成一个字符串进行sha1加密
     * 3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
     *
     * @param param
     * @return
     */
    @Override
    public boolean check(Param param) {
        //1）将token、timestamp、nonce三个参数进行字典序排序
        String[] strs = {token, param.getTimestamp(), param.getNonce()};
        Arrays.sort(strs);
        //2）将三个参数字符串拼接成一个字符串进行sha1加密
        String str = strs[0] + strs[1] + strs[2];
        String mysign = sha1(str);
        System.out.println("加密前：" + str);
        System.out.println("Signature:" + param.getSignature());
        System.out.println("mysign:：" + mysign);
        //3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
        return param.getSignature().equals(mysign);
    }

    /**
     * 使用dom4j包     解析xml数据包  成Map形式
     *
     * @param inputStream
     * @return
     */
    @Override
    public Map<String, String> parseRequest(ServletInputStream inputStream) {
        HashMap<String, String> hashMap = new HashMap<>();
        SAXReader reader = new SAXReader();
        try {
            //读取输入流 回去文档对象
            Document document = reader.read(inputStream);
            //根据文档对象 回去根节点
            Element rootElement = document.getRootElement();
            //根据根节点获取所有的子节点
            List<Element> elements = rootElement.elements();
            for (Element element : elements) {
                hashMap.put(element.getName(), element.getStringValue());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return hashMap;
    }

    /**
     * 用于处理所有的事件和消息de 回复
     * 将Map解析成xml数据包  回复消息
     *
     * @param map
     * @return 返回的是xml数据包
     */
    @Override
    public String getRespose(Map<String, String> map) {
        String msgType = map.get("MsgType");
        String success = "";
        BaseMessage msg = null;
        switch (msgType) {
            case "text":
                msg = dealText(map);
                break;
            case "image":
                msg = dealImage(map);
                break;
            case "voice":
                msg = dealVoice(map);
                break;
            case "video":
                break;
            case "shortvideo":
                break;
            case "location":
                dealLocaltion2(map);
                break;
            case "link":
                break;
            case "event":
                msg = dealEvent(map);
                break;
            default:
                break;
        }
        if (msg != null) {
            String xml = beanToXml(msg);
            log.info(xml);
            return xml;
        } else {
            return success;
        }
    }

    /**
     * 处理位置消息
     *
     * @param map
     */
    private void dealLocaltion2(Map<String, String> map) {
        //获得AccessToken
        String redisToken = getRedisToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
        String access_token = url.replace("ACCESS_TOKEN", redisToken);
        //维度
        String latitude = map.get("Location_X");
        //经度
        String longitude = map.get("Location_Y");
        String fromUserName = map.get("FromUserName");
        String localtion = latitude + "," + longitude;
        log.info("为" + fromUserName + "用户推送当日天气信息");
        String weatherByLocaltion = bdUtil.getWeatherByLocaltion(localtion);
        WeatherResponse response = com.alibaba.fastjson.JSONObject.parseObject(weatherByLocaltion, WeatherResponse.class);
        WeatherResult result = com.alibaba.fastjson.JSONObject.parseObject(response.getResult(), WeatherResult.class);
        ArrayList<Keyworld> keyworlds = new ArrayList<>();
        First first = new First("今天是" + result.getDate() + "，" + result.getWeek() + "", "#173177");
        Keyworld keyworld0 = new Keyworld(result.getCity(), "#173177");
        Keyworld keyworld1 = new Keyworld(result.getWeather(), "#173177");
        Keyworld keyworld2 = new Keyworld(result.getTemplow() + "℃", "#173177");
        Keyworld keyworld3 = new Keyworld(result.getTemphigh() + "℃", "#173177");
        keyworlds.add(keyworld0);
        keyworlds.add(keyworld1);
        keyworlds.add(keyworld2);
        keyworlds.add(keyworld3);
        Remark remark = new Remark("天气转凉，注意添衣保暖，不要感冒了哦^_^", "#173177");
        List<WeatherIndex> index = com.alibaba.fastjson.JSONObject.parseArray(result.getIndex(), WeatherIndex.class);
        StringBuffer sb1 = new StringBuffer();
        for (WeatherIndex weatherIndex : index) {
            Keyworld keyworld11 = new Keyworld(weatherIndex.getIvalue(), "#173177");
            keyworlds.add(keyworld11);
        }
        net.sf.json.JSONObject first1 = net.sf.json.JSONObject.fromObject(first);
        net.sf.json.JSONObject templateData2 = new net.sf.json.JSONObject();
        templateData2.put("first", first1);
        for (int i = 0; i < keyworlds.size(); i++) {
            net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(keyworlds.get(i));
            templateData2.put("keyword" + i, jsonObject);
        }
        templateData2.put("remark", remark);
        WxTemplateMessage wxTemplateMessage1 = new WxTemplateMessage(fromUserName, "amFxIoRc4fCObVXSXZPQf26NZO7xedq_-rrlIRfDApw", "null", null);
        net.sf.json.JSONObject msgData = net.sf.json.JSONObject.fromObject(wxTemplateMessage1);
        msgData.put("data", templateData2.toString());
        System.out.println(msgData);
        httpClient(access_token, "POST", msgData.toString());
    }

    /**
     * 处理声音消息
     * @param map
     * @return
     */
    private BaseMessage dealVoice(Map<String, String> map) {
        String recognition = map.get("Recognition");
        log.info("dealVoice:"+recognition);
        TextMessage msg = null;
        if (recognition.matches(".*天了.*")||recognition.matches(".*多久了.*")){
            Duration between = Duration.between(LocalDateTime.of(2019, 7, 7, 00, 0, 0),LocalDateTime.now());
            String countDay = ("王艺曈和刘世豪已经在一起"+between.toDays()+"天"+between.toHours()%24+"小时"+between.toMinutes()%60+"分钟"+between.getSeconds()%60+"秒了");
            msg = new TextMessage(map,countDay);
        }else if (recognition.matches(".*狗屁.*")){
            msg = new TextMessage(map,"不要讲脏话哦^_^");
        }else if (recognition.matches(".*放屁.*")){
            msg = new TextMessage(map,"这样不文明哦0_0||");
        }else if (recognition.matches(".*二级甲等.*")){
            msg = new TextMessage(map,"阿哦，那可能是评分系统坏了哦(#^.^#)");
        }else if (recognition.matches(".*几号.*")||recognition.matches(".*周几.*")||recognition.matches(".*星期几.*")){
            LocalDateTime now = LocalDateTime.now();
            String format = now.format(DateTimeFormatter.ofPattern("MM月dd号"));
            DayOfWeek dayOfWeek = now.getDayOfWeek();
            msg = new TextMessage(map,"今天是"+format+"   "+dayOfWeek);
        }else if (recognition.matches(".*天气.*")||recognition.matches(".*上海.*")){
            String weather="";
            String city="上海";
            if (recognition.matches(".*郑州.*")){
                city = "郑州";
                weather = bdUtil.getWeatherByCitycode("101180101");
            }else if (recognition.matches(".*周口.*")){
                city = "周口";
                weather = bdUtil.getWeatherByCitycode("101181401");
            }else if (recognition.matches(".*南阳.*")){
                city = "南阳";
                weather = bdUtil.getWeatherByCitycode("101180701");
            }else if (recognition.matches(".*平顶山.*")){
                city = "平顶山";
                weather = bdUtil.getWeatherByCitycode("101180501");
            }else {
                weather = bdUtil.getWeatherByCitycode("101020100");
            }
            WeatherResponse response = com.alibaba.fastjson.JSONObject.parseObject(weather, WeatherResponse.class);
            WeatherResult result = com.alibaba.fastjson.JSONObject.parseObject(response.getResult(), WeatherResult.class);
            List<WeatherDaily> dailies = com.alibaba.fastjson.JSONObject.parseArray(result.getDaily(), WeatherDaily.class);
            First first = new First(city, "#d3a4ff");
//            Remark remark = new Remark("天气转凉，请注意保暖哦！", "#173177");
            ArrayList<Keyworld> keyworlds = new ArrayList<Keyworld>();
            for (WeatherDaily daily : dailies) {
                DayAndNight day = com.alibaba.fastjson.JSONObject.parseObject(daily.getDay(), DayAndNight.class);
                DayAndNight night = com.alibaba.fastjson.JSONObject.parseObject(daily.getNight(), DayAndNight.class);
                Keyworld keyword = new Keyworld(daily.getDate()+"，"+daily.getWeek()+"："+day.getWeather()+"，"+night.getTemplow()+"/"+day.getTemphigh()+"°，"+day.getWinddirect()+"，"+day.getWindpower(),"#173177");
                keyworlds.add(keyword);
            }
            net.sf.json.JSONObject templateData = new net.sf.json.JSONObject();
            net.sf.json.JSONObject first1 = net.sf.json.JSONObject.fromObject(first);
            templateData.put("first",first1);
//            templateData.put("remark",remark1);
            for (int i = 0; i < keyworlds.size() ; i++) {
                net.sf.json.JSONObject keyworld = net.sf.json.JSONObject.fromObject(keyworlds.get(i));
                templateData.put("keyword"+i,keyworld);
            }
            WxTemplateMessage wxTemplateMessage = new WxTemplateMessage(map.get("FromUserName"), "PuqJ8Tv3ZZRF1mVnXxjWAj3uI62RsPbDQ00w7C5pN3A", "https://tianqi.qq.com/index.htm",null);

            //将请求参数对象  转化成 JSON
            net.sf.json.JSONObject msgData = net.sf.json.JSONObject.fromObject(wxTemplateMessage);
            msgData.put("data",templateData.toString());
            System.out.println(msgData);
            String redisToken = getRedisToken();
            String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
            String access_token = url.replace("ACCESS_TOKEN", redisToken);
            httpClient(access_token, "POST", msgData.toString());
        }else{
            msg = new TextMessage(map,"对不起，您的普通话不标准，系统无法识别！快去考个二级甲等的普通话证书再来试试吧(#^.^#)");
        }
        return  msg;
    }

    /**
     * 处理图片消息
     * @param map
     * @return
     */
    private BaseMessage dealImage(Map<String, String> map) {
        String url = map.get("PicUrl");
        String toText = bdUtil.imageToText(url);
        return new TextMessage(map,toText);
    }

    /**
     * 将Map转化成XML数据包  响应给微信服务器
     * @param msg
     * @return
     */
    private String beanToXml(BaseMessage msg) {
        XStream stream = new XStream();
        stream.processAnnotations(TextMessage.class);
        stream.processAnnotations(EventMessage.class);
        stream.processAnnotations(MusicMessage.class);
        stream.processAnnotations(ImageMessage.class);
        stream.processAnnotations(VoiceMessage.class);
        stream.processAnnotations(LocationMessage.class);
        stream.processAnnotations(VideoMessage.class);
        stream.processAnnotations(NewsMessage.class);
        String msgXML = stream.toXML(msg);
        return msgXML;
    }

    /**
     * 处理事件推送
     * @param map
     * @return
     */
    private BaseMessage dealEvent(Map<String, String> map) {
        BaseMessage msg = null;
        String event = map.get("Event");
        switch(event){
            case "CLICK":
                msg = dealClick(map);
                return msg;
            case "VIEW":
                msg = dealView(map);
                return msg;
            case "LOCATION":
//                dealLocaltion(map);
                String fromUserName = map.get("FromUserName");
                if (fromUserName != null){
                    User user = userRepository.findByOpenId(fromUserName);
                    if (user != null){
                        if (map.get("Latitude") != null){
                            user.setLatitude(map.get("Latitude"));
                        }
                        if (map.get("Longitude") != null){
                            user.setLongitude(map.get("Longitude"));
                        }
                        userRepository.save(user);
                    }

                }

                msg = new TextMessage(map,"Hi~ 今天也是充满好运的一天哦！");
                return msg;
            default:
                return msg;
        }
    }

    /**
     * 用户打开公众号对话框
     * 会发送一个Localtion事件    获得当前用户的位置信息  维度和经度
     * 然后调用天气API
     * 解析JSON  成对象  提取字段信息
     * 封装对象   First  Keyword Remake
     * @param map
     */
    private void dealLocaltion(Map<String, String> map) {

        //获得AccessToken
        String redisToken = getRedisToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
        String access_token = url.replace("ACCESS_TOKEN", redisToken);
        //维度
        String latitude = map.get("Latitude");
        //经度
        String longitude = map.get("Longitude");
        String fromUserName = map.get("FromUserName");
        String localtion = latitude+","+longitude;
//        String weather = bdUtil.getWeatherByLocaltion(localtion);

        String isSendWeather = (String) redisUtils.get(fromUserName+"-isSendWeather");
        long isSendWeather1 = redisUtils.getExpire(fromUserName+"-isSendWeather");
        log.error(fromUserName+"用户是否发送过天气信息："+isSendWeather+"，缓存有效时间还剩："+isSendWeather1);
        //如果缓存中的isSendWeather为空  就说明已经过了12个小时还没有发送过天气信息   调用接口发送模板消息
        if (isSendWeather == null) {
            log.info("为"+fromUserName+"用户推送当日天气信息");
            String weatherByLocaltion = bdUtil.getWeatherByLocaltion(localtion);
            WeatherResponse response = com.alibaba.fastjson.JSONObject.parseObject(weatherByLocaltion, WeatherResponse.class);
            WeatherResult result = com.alibaba.fastjson.JSONObject.parseObject(response.getResult(), WeatherResult.class);
            ArrayList<Keyworld> keyworlds = new ArrayList<>();
            First first = new First("今天是" + result.getDate() + "，" + result.getWeek() + "", "#173177");
            Keyworld keyworld0 = new Keyworld(result.getCity(), "#173177");
            Keyworld keyworld1 = new Keyworld(result.getWeather(), "#173177");
            Keyworld keyworld2 = new Keyworld(result.getTemplow() + "℃", "#173177");
            Keyworld keyworld3 = new Keyworld(result.getTemphigh() + "℃", "#173177");
            keyworlds.add(keyworld0);
            keyworlds.add(keyworld1);
            keyworlds.add(keyworld2);
            keyworlds.add(keyworld3);
            Remark remark = new Remark("天气转凉，注意添衣保暖，不要感冒了哦^_^", "#173177");
            List<WeatherIndex> index = com.alibaba.fastjson.JSONObject.parseArray(result.getIndex(), WeatherIndex.class);
            StringBuffer sb1 = new StringBuffer();
            for (WeatherIndex weatherIndex : index) {
                Keyworld keyworld11 = new Keyworld(weatherIndex.getIvalue(), "#173177");
                keyworlds.add(keyworld11);
            }
            net.sf.json.JSONObject first1 = net.sf.json.JSONObject.fromObject(first);
            net.sf.json.JSONObject templateData2 = new net.sf.json.JSONObject();
            templateData2.put("first", first1);
            for (int i = 0; i < keyworlds.size(); i++) {
                net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(keyworlds.get(i));
                templateData2.put("keyword" + i, jsonObject);
            }
            templateData2.put("remark", remark);
            WxTemplateMessage wxTemplateMessage1 = new WxTemplateMessage(fromUserName, "amFxIoRc4fCObVXSXZPQf26NZO7xedq_-rrlIRfDApw", "null", null);
            net.sf.json.JSONObject msgData = net.sf.json.JSONObject.fromObject(wxTemplateMessage1);
            msgData.put("data", templateData2.toString());
            System.out.println(msgData);
            String post = httpClient(access_token, "POST", msgData.toString());
            redisUtils.set(fromUserName+"-isSendWeather","1",60*60*12);
        }else {
            return;
        }
    }

    public String httpClient(String Url,String RequestMethod,String data){
        StringBuffer sb = null;
        try {
//            建立连接
            URL url = new URL(Url);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setDoInput(true);
            httpUrlConn.setDoOutput(true);
            String s = RequestMethod.toUpperCase();
            httpUrlConn.setRequestMethod(s);
            httpUrlConn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            if ("GET".equalsIgnoreCase(RequestMethod)){
                httpUrlConn.connect();
            }else {
                //设置请求头   //设置参数类型是json格式
                //httpUrlConn.connect();     可要    可不要
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(httpUrlConn.getOutputStream(), "UTF-8"));
                writer.write(data);
                writer.close();
                // 获取输入流
            }
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            // 读取返回结果
            sb = new StringBuffer();
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                sb.append(str);
            }
            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            httpUrlConn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(sb);
        log.info(sb.toString());
        return sb.toString();
    }
    /**
     * 处理事件推送  视图
     * @param map
     * @return
     */
    private BaseMessage dealView(Map<String, String> map) {
        return null;
    }
    /**
     * 处理Click菜单
     * 处理事件推送  点击事件
     * @param map
     * @return
     */
    private BaseMessage dealClick(Map<String, String> map) {
        String eventKey = map.get("EventKey");
        switch (eventKey){
            case "V1001_TODAY_VIDEO":
                FastDFSFile fastDFSFile1 = fastDFSFileRepository.findFastDFSFileByVideoId((int)(0 + (Math.random()* (3 - 0))));
                if (fastDFSFile1 != null){
                    Video video = new Video();
                    video.setDescription(fastDFSFile1.getDescription());
                    video.setTitle(fastDFSFile1.getName());
                    video.setMediaId(fastDFSFile1.getUrl());
                    VideoMessage videoMessage = new VideoMessage(map,video);
                    return videoMessage;
                }else {
                    return new TextMessage(map,"Sorry~ 今日无影片");
                }
            case "V1002_TODAY_MUSIC":
                FastDFSFile fastDFSFile = fastDFSFileRepository.findFastDFSFileByMusicId((int)(0 + (Math.random()* (17 - 0))));
                if (fastDFSFile != null){
                    Music music = new Music();
                    music.setTitle(fastDFSFile.getName());
                    music.setDescription(fastDFSFile.getDescription());
                    //https://wangyitong.club/group1/M00/00/00/rB52RF-O-b-APHtOAEW_f4JXtVY979.mp3
                    music.setMusicURL(fastDFSFile.getUrl());
                    music.setHQMusicUrl(fastDFSFile.getUrl());
                    music.setThumbMediaId("gAGEkIl7qY8y8pGWJRQYBQqtl7Nj01bM6j8zpeTQzehDSbIYFteAsMO_9ED3tL2l");
                    MusicMessage musicMessage = new MusicMessage(map,music);
                    return musicMessage;
                }else {
                    return new TextMessage(map,"今日也米有音乐，现在版权意识多强啊，没有VIP怎么听音乐？支持一下博主的文章吧！");
                }
            case "V1003_TODAY_NEWS":
                //国内焦点  5572a108b3cdc86cf39001cd
                Item[] news3 = newUtil.getNews("5572a108b3cdc86cf39001cd");
                NewsMessage newsMessage1 = new NewsMessage(map,news3 );
                newsMessage1.setArticleCount(8);
                return newsMessage1 ;
            case "V1004_TODAY_NEWS":
                //国际焦点  5572a108b3cdc86cf39001ce
                Item[] news4 = newUtil.getNews("5572a108b3cdc86cf39001ce");
                NewsMessage newsMessage2 = new NewsMessage(map,news4 );
                newsMessage2.setArticleCount(8);
                return newsMessage2 ;
            case "V1005_TODAY_NEWS":
                //国内最新 5572a109b3cdc86cf39001db
                Item[] news5 = newUtil.getNews("5572a109b3cdc86cf39001db");
                NewsMessage newsMessage3 = new NewsMessage(map,news5 );
                newsMessage3.setArticleCount(8);
                return newsMessage3 ;
            case "V1006_TODAY_NEWS":
                //娱乐焦点  5572a108b3cdc86cf39001d5
                Item[] news6 = newUtil.getNews("5572a108b3cdc86cf39001d5");
                NewsMessage newsMessage4 = new NewsMessage(map,news6 );
                newsMessage4.setArticleCount(8);
                return newsMessage4 ;
            case "V1007_TODAY_NEWS":
                //国际最新  5572a109b3cdc86cf39001de
                Item[] news7 = newUtil.getNews("5572a109b3cdc86cf39001de");
                NewsMessage newsMessage7 = new NewsMessage(map,news7 );
                newsMessage7.setArticleCount(8);
                return newsMessage7 ;
            default:
                return new TextMessage(map,"Hello World！");
        }
    }

    /**
     * 处理文本消息
     * @param map
     * @return
     */
    private BaseMessage dealText(Map<String, String> map) {
        String content1 = map.get("Content");
        new Thread(() ->{
            UserText userText = new UserText();
            userText.setOpenID(map.get("FromUserName"));
            userText.setText(content1);
            userTextRepository.save(userText);
        }).start();
        TextMessage textMessage =null;

        log.info("dealText:"+content1);
       if (content1.matches(".*几天了*")){
            Duration between = Duration.between(LocalDateTime.of(2019, 7, 7, 00, 0, 0),LocalDateTime.now());
            String countDay = ("王艺曈和刘世豪已经在一起"+between.toDays()+"天"+between.toHours()%24+"小时"+between.toMinutes()%60+"分钟"+between.getSeconds()%60+"秒了");
            textMessage = new TextMessage(map,countDay);
        }else if (content1.matches(".*什么功能.*")||content1.matches(".*会干什么.*")){
            textMessage = new TextMessage(map,"我会的可多了哦：识别图片文字、查询天气情况，还可以成语接龙哦！来试试吧");
        }else if (content1.matches(".*几号.*")||content1.matches(".*周几.*")||content1.matches(".*星期几.*")){
            LocalDateTime now = LocalDateTime.now();
            String format = now.format(DateTimeFormatter.ofPattern("MM月dd号"));
            DayOfWeek dayOfWeek = now.getDayOfWeek();
            String week = "";
           switch (dayOfWeek){
               case MONDAY:
                   week = "星期一";
                   break;
               case TUESDAY:
                   week = "星期二";
                   break;
               case WEDNESDAY:
                   week = "星期三";
                   break;
               case THURSDAY:
                   week = "星期四";
                   break;
               case FRIDAY:
                   week = "星期五";
                   break;
               case SATURDAY:
                   week = "星期六";
                   break;
               default:
                   week = "星期天";
                   break;
           }
            return new TextMessage(map,"今天是"+format+"  "+week);
        }else if (content1.matches(".*天气.*")||content1.matches(".*上海.*")){
            String weather="";
            String city="上海";
            if (map.get("Content").matches(".*郑州.*")){
                city="郑州";
                 weather = bdUtil.getWeatherByCitycode("101180101");
            }else if (map.get("Content").matches(".*周口.*")){
                city="周口";
                 weather = bdUtil.getWeatherByCitycode("101181401");
            }else if (map.get("Content").matches(".*南阳.*")){
                city="南阳";
                 weather = bdUtil.getWeatherByCitycode("101180701");
            }else if (map.get("Content").matches(".*平顶山.*")){
                city="平顶山";
                 weather = bdUtil.getWeatherByCitycode("101180501");
            }else {
                 weather = bdUtil.getWeatherByCitycode("101020100");
            }
            WeatherResponse response = com.alibaba.fastjson.JSONObject.parseObject(weather, WeatherResponse.class);
            WeatherResult result = com.alibaba.fastjson.JSONObject.parseObject(response.getResult(), WeatherResult.class);
            List<WeatherDaily> dailies = com.alibaba.fastjson.JSONObject.parseArray(result.getDaily(), WeatherDaily.class);
            First first = new First(city, "#d3a4ff");
//            Remark remark = new Remark("天气转凉，请注意保暖哦！", "#173177");
            ArrayList<Keyworld> keyworlds = new ArrayList<Keyworld>();
            for (WeatherDaily daily : dailies) {
                DayAndNight day = com.alibaba.fastjson.JSONObject.parseObject(daily.getDay(), DayAndNight.class);
                DayAndNight night = com.alibaba.fastjson.JSONObject.parseObject(daily.getNight(), DayAndNight.class);
                Keyworld keyword = new Keyworld(daily.getDate()+"，"+daily.getWeek()+"："+day.getWeather()+"，"+night.getTemplow()+"/"+day.getTemphigh()+"°，"+day.getWinddirect()+"，"+day.getWindpower(),"#173177");
                keyworlds.add(keyword);
            }
            net.sf.json.JSONObject templateData = new net.sf.json.JSONObject();
            net.sf.json.JSONObject first1 = net.sf.json.JSONObject.fromObject(first);
//            net.sf.json.JSONObject remark1 = net.sf.json.JSONObject.fromObject(remark);
            templateData.put("first",first1);
//            templateData.put("remark",remark1);
            for (int i = 0; i < keyworlds.size() ; i++) {
                net.sf.json.JSONObject keyworld = net.sf.json.JSONObject.fromObject(keyworlds.get(i));
                templateData.put("keyword"+i,keyworld);
            }
            WxTemplateMessage wxTemplateMessage = new WxTemplateMessage(map.get("FromUserName"), "PuqJ8Tv3ZZRF1mVnXxjWAj3uI62RsPbDQ00w7C5pN3A", "https://tianqi.qq.com/index.htm",null);

            //将请求参数对象  转化成 JSON
            net.sf.json.JSONObject msgData = net.sf.json.JSONObject.fromObject(wxTemplateMessage);
            msgData.put("data",templateData.toString());
            System.out.println(msgData);
            String redisToken = getRedisToken();
            String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
            String access_token = url.replace("ACCESS_TOKEN", redisToken);
            httpClient(access_token, "POST", msgData.toString());
//            textMessage = new TextMessage(map,bdUtil.dealWeatherStr(weather));
        }else {
            String content = map.get("Content");
            if(content.matches(".*成语接龙.*")){
                String a = "输入\"CYJL空格成语\"就可以可以一起玩成语接龙啦";
                textMessage = new TextMessage(map,a);
            }else if(content.matches(".*CYJL.*")){
                String substring = content.substring(5);
                content = "@cy"+substring;
                String url = "http://i.itpk.cn/api.php?limit=2&api_key=d3a6d81922f222a3b6c05d0b81c66e8b&api_secret=liushihao123&question="+content;
                String get = httpClient(url, "GET", null);
                textMessage = new TextMessage(map,get);
            }else{
                String url = "http://i.itpk.cn/api.php?limit=2&api_key=d3a6d81922f222a3b6c05d0b81c66e8b&api_secret=liushihao123&question="+content;
                String get = httpClient(url, "GET", null);
                textMessage = new TextMessage(map,get);
            }

        }
        return textMessage;
    }

    /**
     * 获取acces_token
     * https请求方式: GET
     * https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
     * @return
     */
    public static String getWXToken() throws Exception {
        final String host = "https://api.weixin.qq.com";
        final String appID = "wx4959a20a2a31b3fc";
        final String appsecret = "d0e97bd7be270bc400734e385eb1ad0e";
        final String path = "/cgi-bin/token";
        final String replace = path.replace("APPID", appID).replace("APPSECRET", appsecret);
        Map<String, String> headers = new HashMap<String, String>();
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("grant_type","client_credential");
        querys.put("appid",appID);
        querys.put("secret",appsecret);
        HttpResponse httpResponse = HttpUtils.doGet(host, replace, headers, querys);
        String s = EntityUtils.toString(httpResponse.getEntity());
        JSONObject jsonObject = JSON.parseObject(s);
        String access_token = jsonObject.getString("access_token");
        return access_token;
    }

    /**
     * 获得二维码的ticket
     * 临时二维码请求说明
     * http请求方式: POST URL: https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN
     * {"ticket":"gQGz8DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAycUZUUGhsOXZmakUxUURhN052Y2gAAgSnD75fAwSAOgkA","expire_seconds":604800,"url":"http:\/\/weixin.qq.com\/q\/02qFTPhl9vfjE1QDa7Nvch"}
     * @return
     */
    public  String getQRCodeTicket() throws Exception {
        String host = "https://api.weixin.qq.com";
        String path = "/cgi-bin/qrcode/create";
        String token = WXServiceImpl.getWXToken();
        Map<String, String> headers = new HashMap<String, String>();
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("access_token",token);
        String data= "{\"expire_seconds\": 604800, \"action_name\": \"QR_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"lsh\"}}}";
        HttpResponse httpResponse = HttpUtils.doPost(host, path, headers, querys, data);
        String respJsonStr = EntityUtils.toString(httpResponse.getEntity());
        JSONObject jsonObject = JSON.parseObject(respJsonStr);
        System.out.println("jsonObject:"+jsonObject);
        String ticket = (String)jsonObject.get("ticket");

        return ticket;
    }

    /**
     * HTTP GET 请求（请使用https协议）
     * https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET
     * 提醒：TICKET记得进行UrlEncode
     * 使用ticket换取二维码
     * @param ticket
     * @return
     */
    public static void QRCode(String ticket) throws Exception {
        String host = "https://mp.weixin.qq.com";
        String path = "/cgi-bin/showqrcode";
        Map<String, String> headers = new HashMap<String, String>();
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("ticket",ticket);
        HttpResponse httpResponse = HttpUtils.doGet(host, path, headers, querys);
        //直接使用get请求浏览器访问 二维码
    }

    private String sha1(String str) {
        StringBuilder sb = new StringBuilder();
        try {
            //获取一个加密对象
            MessageDigest md = MessageDigest.getInstance("sha1");
            //加密
            byte[] digest = md.digest(str.getBytes());
            char[] chars = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};

            //处理加密结果
            for (byte b : digest){
                sb.append(chars[(b>>4)&15]);
                sb.append(chars[b&15]);
            }

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }


}
